package com.sfc.sdsr.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.sfc.sdsr.server.dao.DaoFactory;

public class TestServer {
	private final Logger log = Logger.getLogger(getClass());
	private static final int PORT = 4444;

	public static void main(String[] args) {

		TestServer testServer = new TestServer();
		testServer.run();
	}

	public void run() {
		// have a UTC timestamp of last modified database;
		// clients use their last successful update UTC to send to server
		// maybe have minor update UTC vs major update UTC
		// or multiplse UTC for different kinds of stuff

		// users has different kinds of groups, leaders, music min, member
		// different groups gets to add content to their page

		// server runs derby ??
		// or externally to some mysql db

		/*
		 * 1 Byte is 8 bits, XX
		 * Byte (1 bytes) Max Value: 127 
		 * Short (2 bytes) Max Value: 32767
		 * Int (4 bytes) Max Value: 2147483647
		 * Long (8 bytes) Max Value: 9223372036854775807
		 */
		try {
			File sfcProperties = new File("server.properties");
			InputStream is = new FileInputStream(sfcProperties);
			
			Properties properties = new Properties();
			properties.load(is);

			DaoFactory.setDao(properties.getProperty(SfcProperties.DAO.name()));
			
			ServerSocket serverSocket = new ServerSocket(PORT);
			Socket socket;
			log.info("Test server (" + serverSocket.getInetAddress().toString() + ") started. Listening on port: " + PORT);
			while (true) {
				socket = serverSocket.accept();
				log.info("Dispatching Request from " + socket.getInetAddress().getHostAddress());
				RequestHandler requestHandler = new RequestHandler(socket, properties);
				new Thread(requestHandler).start();
			}
		} catch (IOException e) {
			log.error("IOException: " + e.getMessage());
		}
	}

}
